回到官網提供的IoC Container的圖,可以知道Spring Container將POJO與設定檔資訊合在一起,然後生產出物件,那麼這當中有什麼樣的細節呢,就是今日想要探討的主題。
參考網址
public class User {
private String name;
private String gender;
private String email;
//getter、setter、toString 略
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="user01" class="com.swj.User">
<property name="name" value="James"></property>
<property name="gender" value="male"></property>
<property name="email" value="abc@test.com.tw"></property>
</bean>
</beans>
@Test
public void TestIoC(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
User user = (User)ioc.getBean("user01");
System.out.println(user);
}
透過子類別ClassPathXmlApplicationContext將設定檔資訊載入到IoC容器中
在getBean的方法中傳入設定檔中設定的id
容器創建完成,物件也創建完成
稍微修改一下上面的範例,加入constructor
public class User {
private String name;
private String gender;
private String email;
public User() {
System.out.println("user物件生成");;
}
//getter、setter、toString 略
@Test
public void TestIoC(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
System.out.println("IoC container prepared....");
User user = (User)ioc.getBean("user01");
System.out.println(user);
}
Result
向容器取得同一個id兩次進行測試
@Test
public void TestIoC(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
System.out.println("IoC container prepared....");
User user1 = (User)ioc.getBean("user01");
User user2 = (User)ioc.getBean("user01");
System.out.println(user1 == user2);
}
Result
NoSuchBeanDefinitionException
@Test
public void TestIoC(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
System.out.println("IoC container prepared....");
User user = (User)ioc.getBean("user123456");
}
Result
修改setter方法
public class User {
public class User {
private String name;
private String gender;
private String email;
public User() {
System.out.println("user物件生成");;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", gender='" + gender + '\'' +
", email='" + email + '\'' +
'}';
}
public String getName() {return name;}
public void setName(String name) {
System.out.println("調用setName");
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
System.out.println("調用setGender");
this.gender = gender;
}
public String getEmail() {return email;}
public void setEmail(String email) {
System.out.println("調用setEmail");
this.email = email;
}
}
@Test
public void TestIoC(){
ApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");
System.out.println("IoC container prepared....");
User user = (User)ioc.getBean("user01");
}
Result